<?php
declare(strict_types=1);

namespace plugin\ky_black\app\admin\controller;

use plugin\ky_black\app\admin\model\Organization;
use plugin\ky_black\app\admin\validate\OrganizationValidate;
use support\Request;
use plugin\ky_black\app\admin\model\User;

class OrganizationController extends BaseController
{
    /**
     * 获取企业列表
     */
    public function index(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);
        $keyword = $request->input('keyword', '');
        $status = $request->input('status', '');

        $query = Organization::query();
        
        if ($keyword) {
            $query->where(function ($q) use ($keyword) {
                $q->where('company_name', 'like', "%{$keyword}%")
                  ->orWhere('business_license', 'like', "%{$keyword}%")
                  ->orWhere('tax_number', 'like', "%{$keyword}%");
            });
        }
        
        if ($status !== '') {
            $query->where('status', (int)$status);
        }

        $total = $query->count();
        $list = $query->offset(($page - 1) * $limit)
                     ->limit($limit)
                     ->orderBy('created_at', 'desc')
                     ->get();

        // 获取关联的用户
        foreach ($list as $org) {
            $user = User::where('org_id', $org->org_id)
                ->where('type', 'organization')
                ->first();
            $org->user_id = $user ? $user->user_id : null;
        }

        return $this->success([
            'list' => $list,
            'total' => $total
        ]);
    }

    /**
     * 添加企业
     */
    public function create(Request $request)
    {
        $data = $request->post();
        
        // 处理空字符串的black_card_no
        if (isset($data['black_card_no']) && $data['black_card_no'] === '') {
            $data['black_card_no'] = null;
        }
        
        // 添加调试日志
        error_log("Create organization data: " . json_encode($data));
        
        // 先检查是否存在
        $exists = Organization::query()
            ->where('business_license', $data['business_license'])
            ->first();
        
        error_log("Exists check result: " . ($exists ? 'true' : 'false'));
        
        if ($exists) {
            error_log("Found existing record: " . json_encode($exists));
            return $this->error('营业执照号已存在');
        }
        
        // 验证数据
        $validate = new OrganizationValidate();
        if (!$validate->check($data)) {
            error_log("Validation error: " . $validate->getError());
            return $this->error($validate->getError());
        }

        try {
            $org = new Organization();
            $org->fill($data);
            $org->save();
            
            return $this->success($org, '添加成功');
        } catch (\Exception $e) {
            error_log("Save error: " . $e->getMessage());
            return $this->error('添加失败：' . $e->getMessage());
        }
    }

    /**
     * 更新企业信息
     */
    public function update(Request $request)
    {
        $data = $request->post();
        $orgId = $request->input('org_id');
        
        if (!$orgId) {
            return $this->error('参数错误');
        }

        // 验证数据
        $validate = new OrganizationValidate();
        if (!$validate->scene('update')->check($data)) {
            return $this->error($validate->getError());
        }

        try {
            $org = Organization::find($orgId);
            if (!$org) {
                return $this->error('企业不存在');
            }

            // 记录变更
            $changes = [];
            foreach ($data as $field => $value) {
                if ($org->$field != $value) {
                    $changes[] = [
                        'field' => $field,
                        'old' => $org->$field,
                        'new' => $value
                    ];
                }
            }

            $org->fill($data);
            $org->save();

            // 保存变更记录
            if (!empty($changes)) {
                foreach ($changes as $change) {
                    $org->changes()->create([
                        'change_type' => $this->getChangeType($change['field']),
                        'change_field' => $change['field'],
                        'old_value' => $change['old'],
                        'new_value' => $change['new'],
                        'operator_id' => $request->user->staff_id,
                        'operator_name' => $request->user->real_name
                    ]);
                }
            }
            
            return $this->success($org, '更新成功');
        } catch (\Exception $e) {
            return $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 获取企业详情
     */
    public function detail(Request $request)
    {
        // 从params中获取id
        $params = $request->get('params', []);
        $orgId = isset($params['id']) ? $params['id'] : null;
        
        if (!$orgId) {
            return $this->error('参数错误');
        }

        // 获取企业信息，同时加载关联的黑卡信息
        $org = Organization::with(['blackCard'])->find($orgId);
        if (!$org) {
            return $this->error('企业不存在');
        }

        // 获取关联的用户信息
        $user = User::where('org_id', $org->org_id)
            ->where('type', 'organization')
            ->first();

        // 格式化一些字段
        $org->status_text = $org->status ? '正常' : '禁用';
        $org->invoice_type_text = $org->invoice_type === 'normal' ? '普票' : '专票';
        
        // 添加用户ID
        $org->user_id = $user ? $user->user_id : null;

        return $this->success($org);
    }

    /**
     * 更改企业状态
     */
    public function status(Request $request)
    {
        $orgId = $request->input('org_id');
        $status = $request->input('status');
        
        if (!$orgId || !in_array($status, [0, 1])) {
            return $this->error('参数错误');
        }

        try {
            $org = Organization::find($orgId);
            if (!$org) {
                return $this->error('企业不存在');
            }

            $oldStatus = $org->status;
            $org->status = $status;
            $org->save();

            // 记录状态变更
            $org->changes()->create([
                'change_type' => 'status',
                'change_field' => 'status',
                'old_value' => $oldStatus,
                'new_value' => $status,
                'operator_id' => $request->user->staff_id,
                'operator_name' => $request->user->real_name
            ]);
            
            return $this->success(null, '状态更新成功');
        } catch (\Exception $e) {
            return $this->error('状态更新失败：' . $e->getMessage());
        }
    }

    /**
     * 获取变更类型
     */
    private function getChangeType($field)
    {
        $typeMap = [
            'company_name' => 'basic',
            'business_license' => 'basic',
            'legal_representative' => 'basic',
            'company_address' => 'basic',
            'contact_phone' => 'contact',
            'company_email' => 'contact',
            'contact_name' => 'contact',
            'contact_mobile' => 'contact',
            'invoice_type' => 'invoice',
            'tax_number' => 'invoice',
            'bank_name' => 'invoice',
            'bank_account' => 'invoice',
            'invoice_address' => 'invoice',
            'invoice_phone' => 'invoice',
            'status' => 'status'
        ];
        
        return $typeMap[$field] ?? 'other';
    }
} 